/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package struts.action;

import dao.DAOFacade;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import pojo.Arquivos;
import pojo.Usuario;
import struts.form.ArquivoForm;

/**
 *
 * @author samuel
 */
public class ArquivoAction extends Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String CAMINHO_SERVIDOR = DAOFacade.getInstance().buscarConfiguracao().getCaminho();

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ArquivoForm myForm = (ArquivoForm) form;

        //Grava o arquivo passado no servidor
        FormFile myFile = myForm.getMyFile();
        String fileName = myFile.getFileName();
        int fileSize = myFile.getFileSize();
        byte[] fileData = myFile.getFileData();

        File file = new File(CAMINHO_SERVIDOR + fileName);
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(fileData);
        fileOutputStream.close();

        //colocando um usuario na sessao. Isso deveria ser feito quando o usuario logasse no sistema
        request.getSession().setAttribute("usuario", DAOFacade.getInstance().buscaUsuario(1));

        //salva no banco os dados do arquivo e do usuario que fez o upload
        DAOFacade.getInstance().inserirArquivo(new Arquivos((Usuario) request.getSession().getAttribute("usuario"), CAMINHO_SERVIDOR + fileName));

        return mapping.findForward(SUCCESS);
    }
}
